package com.zjh.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/", "/index").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        http.formLogin().
                //这是指定我们的登录页面
                        loginPage("/toiLogin").
                //这是指定登录成功后的跳转链接，一般是form表单的action链接
                        loginProcessingUrl("/usr/login").
                //用户名参数名称
                        usernameParameter("username").
                //密码参数名称
                        passwordParameter("password").
                //这是指定登录成功后的跳转链接，一般是form表单的action链接
                        defaultSuccessUrl("/index").
                //这是跳转成功后，URl地址显示
                        successForwardUrl("/index").
                //这是跳转失败后，url地址栏显示
                        failureForwardUrl("/error");

        //跨站请求伪造保护
        http.csrf().disable();

        http.logout().logoutSuccessUrl("/");

        //开启记住我功能 默认两周
        http.rememberMe().rememberMeParameter("remember");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zzz").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2")
                .and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
                .and()
                .withUser("user").password(new BCryptPasswordEncoder().encode("123456")).roles("vip3");
    }
}
